<template>
  <el-card>
    <div slot="header">
      <span>{{ title }}</span>
    </div>
    <el-divider content-position="left">考察计划信息</el-divider>
    <el-row>
      <el-form
        class="table_form_wrap"
        ref="planForm"
        :model="planForm"
        :rules="formValidate"
        label-width="140px"
      >
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input
              v-model.trim="planForm.planName"
              placeholder="请输入计划名称"
              show-word-limit
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="计划时间" prop="planTime">
            <el-date-picker
              :clearable="false"
              v-model="planForm.planTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="出差地点" prop="businessTripPlace">
            <el-input
              v-model.trim="planForm.businessTripPlace"
              placeholder="请输入出差地点"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交通工具" prop="vehicle">
            <el-select
              v-model.trim="planForm.vehicle"
              placeholder="请选择交通工具"
              filterable
            >
              <el-option
                v-for="item in vehicleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="计划拟定人" prop="createUser">
            <el-input
              readonly
              v-model.trim="planForm.createUser"
            />
          </el-form-item>
          <el-form-item label="出差人员" prop="personListStr">
            <el-input
              readonly
              v-model="planForm.personListStr"
              placeholder="请选择出差人员"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="showHrUserDialog"
              ></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-divider content-position="left">工作任务明细</el-divider>
    <el-row>
      <el-form
        class="table_form_wrap"
        ref="taskForm"
        :model="taskForm"
        label-width="120px"
      >
        <el-row
          v-for="(item, index) in taskForm.detailList"
          :key="index"
        >
          <el-card class="box-card" shadow="never">
            <el-col :span="8">
              <el-form-item
                label="供应商名称"
                :prop="'detailList.'+ index +'.supplierName'"
                :rules="[{ required: true, message: '供应商不能为空', trigger: ['change', 'blur']}]"
              >
                <el-input readonly v-model="item.supplierName" placeholder="请选择供应商">
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="showSupplierDialog(index)"
                  ></el-button>
                </el-input>
              </el-form-item>
              <el-form-item
                label="供应商分类"
                :prop="'detailList.'+ index +'.supplierClassifyName'"
                :rules="[{ required: true, message: '供应商分类不能为空', trigger: 'change'}]"
              >
                <el-input disabled v-model="item.supplierClassifyName" :placeholder="plochoderS" />
              </el-form-item>
              <el-form-item
                label="供应商性质"
                :prop="'detailList.'+ index +'.supplierNatureName'"
              >
                <el-input disabled v-model="item.supplierNatureName" :placeholder="plochoderS" />
              </el-form-item>
              <el-form-item
                label="详细地址"
                :prop="'detailList.'+ index +'.registerAddress'"
                :rules="[{ required: true, message: '详细地址不能为空', trigger: 'change'}]"
              >
                <el-input disabled v-model="item.registerAddress" :placeholder="plochoderS" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="供应商联系人"
                :prop="'detailList.'+ index +'.contactId'"
                :rules="[{ required: true, message: '供应商联系人不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.contactId"
                  placeholder="请选择供应商联系人"
                  filterable
                  @change="(val) => {handelPersonSelect(val, item)}"
                >
                  <el-option
                    v-for="option in item.contactPersonOptions"
                    :key="option.id"
                    :value="option.id"
                    :label="option.personName"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="联系电话"
                :prop="'detailList.'+ index +'.contactPhone'"
                :rules="[{ required: true, message: '联系电话不能为空', trigger: 'change'}]"
              >
                <el-input disabled v-model="item.contactPhone" :placeholder="plochoderP" />
              </el-form-item>
              <el-form-item
                label="职务"
                :prop="'detailList.'+ index +'.contactPosition'"
                :rules="[{ required: true, message: '职务不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.contactPosition"
                  :placeholder="plochoderP"
                  disabled
                >
                  <el-option
                    v-for="option in JOB_TITLE_SELECT_LIST"
                    :key="option.value"
                    :value="option.value"
                    :label="option.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="考察类型"
                :prop="'detailList.'+ index +'.inspectType'"
                :rules="[{ required: true, message: '考察类型不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.inspectType"
                  placeholder="请选择考察类型"
                  filterable
                >
                  <el-option
                    v-for="option in inspectTypeOptions"
                    :key="option.value"
                    :value="option.value"
                    :label="option.label"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="考察目的"
                :prop="'detailList.'+ index +'.target'"
                :rules="[{ required: true, message: '考察目的不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.target"
                  placeholder="请选择考察目的"
                  filterable
                  multiple
                  collapse-tags
                >
                  <el-option
                    v-for="option in targetOptions"
                    :key="option.value"
                    :value="option.value"
                    :label="option.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="是否新渠道"
                :prop="'detailList.'+ index +'.newChannel'"
                :rules="[{ required: true, message: '是否新渠道不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.newChannel"
                  placeholder="请选择是否新渠道"
                  filterable
                >
                  <el-option
                    v-for="option in whetherOrNotOptions"
                    :key="option.value"
                    :value="option.value"
                    :label="option.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="是否已报价"
                :prop="'detailList.'+ index +'.quote'"
                :rules="[{ required: true, message: '是否已报价不能为空', trigger: 'change'}]"
              >
                <el-select
                  v-model="item.quote"
                  placeholder="请选择是否已报价"
                  filterable
                >
                  <el-option
                    v-for="option in whetherOrNotOptions"
                    :key="option.value"
                    :value="option.value"
                    :label="option.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="报价单"
                :prop="'detailList.'+ index +'.quoteFile'"
                :rules="[{ required: item.quote, message: '报价单不能为空', trigger: 'blur'}]"
              >
                <el-upload
                  class="upload-demo"
                  :limit="1"
                  action="/srm-admin/annex/upload"
                  accept=".doc, .docx, .xls, .xlsx, .pdf, .pptx, .ppt"
                  :on-remove="onRemove.bind(null, item)"
                  :on-success="onUploadsuccess.bind(null, {'index': index, 'data': item})"
                  :before-upload="beforeFileUpload.bind(null, {'data': item})"
                  :on-error="onUploadError"
                  :fileList="item.fileList"
                >
                  <el-button
                    type="primary"
                    size="small"
                  >上传报价单</el-button>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <div class="del-btn" v-if="taskForm.detailList.length > 1">
                <el-button
                  size="mini"
                  icon="el-icon-close"
                  circle
                  @click="removeRow(index)"
                ></el-button>
              </div>
            </el-col>
            <el-col :span="22">
              <el-form-item
                label="现阶段合作情况"
                :prop="'detailList.'+ index +'.situation'"
                :rules="[{ required: true, message: '现阶段合作情况不能为空', trigger: 'blur'}]"
              >
                <el-input
                  v-model.trim="item.situation"
                  placeholder="请输入现阶段合作情况"
                  :maxlength="100"
                  show-word-limit
                  type="textarea"
                  rows="1"
                />
              </el-form-item>
            </el-col>
          </el-card>
        </el-row>
        <el-row type="flex" justify="center">
          <el-button
            round
            plain
            type="primary"
            class="add-btn"
            size="mini"
            icon="el-icon-plus"
            @click="addRow()"
          >
            新增任务明细
          </el-button>
        </el-row>
      </el-form>
    </el-row>
    <el-row type="flex" justify="center" class="footer">
      <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提交</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleSave">暂存</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-row>
    <HrUserDialog
      :hrUserVisible.sync="dialogVisible"
      :personList="planForm.personList"
      @handle-select="handleGetUserList"
    />
    <SelectSupplierDialog
      :supplierVisible.sync="supplierDialogVisible"
      @handle-select="handleGetSupplierInfo"
    />
  </el-card>
</template>
<script>
import HrUserDialog from '@supplier/components/SelectHrUser'
import SelectSupplierDialog from './components/SelectSupplierDialog'
import {
  queryPlanDetailService,
  querySupplierPersonInfoService,
  addPlanService,
  stashPlanService
} from '@api/supplier/returnVisteManage';
import { batchQuerySupplierInfoService } from '@api/supplier/components';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';
import { WHETHER_OR_NOT_OPTIONS, VEHICLE_OPTIONS, JOB_TITLE_SELECT_LIST } from './constants';
import { INSPECTION_TARGET_OPTIONS, INSPECTION_TYPE_OPTIONS } from '@/pages/supplier/constants/common'

export default {
  components: {
    HrUserDialog,
    SelectSupplierDialog
  },
  data () {
    return {
      JOB_TITLE_SELECT_LIST, // 职务
      plochoderP: '根据供应商联系人带出',
      plochoderS: '根据供应商带出',
      itemIndex: null,
      fileParamSingle: {},
      id: null,
      submitLoading: false,
      dialogVisible: false,
      supplierDialogVisible: false,
      vehicleOptions: VEHICLE_OPTIONS, // 交通工具
      whetherOrNotOptions: WHETHER_OR_NOT_OPTIONS,
      inspectTypeOptions: INSPECTION_TYPE_OPTIONS, // 考察类型列表
      targetOptions: INSPECTION_TARGET_OPTIONS, // 考察目的列表
      planForm: {
        id: '',
        planName: '', // 计划名称
        planCode: '', // 计划编码
        planTime: '', // 计划时间
        startTime: '', // 计划开始时间
        endTime: '', // 计划开始时间
        businessTripPlace: '', // 出差地点
        vehicle: '', // 交通工具
        personList: [], // 出差人员
        personListStr: '', // 出差人员
        detailList: [], // 工作明细 考察详情
        createUser: '', // 计划拟定人
        createUserId: '', // 计划拟定人
      },
      formValidate: {
        planName: [
          { required: true, message: '计划名称不能为空', trigger: 'blur' }
        ],
        planTime: [
          { required: true, message: '计划时间不能为空', trigger: 'change' }
        ],
        businessTripPlace: [
          { required: true, message: '出差地点不能为空', trigger: 'blur' }
        ],
        vehicle: [
          { required: true, message: '交通工具不能为空', trigger: 'change' }
        ],
        createUser: [{ required: true, message: '计划拟定人不能为空', trigger: 'blur' }],
        personListStr: [{ required: true, message: '出差人员不能为空', trigger: 'change' }],
      },
      // 工作任务明细
      taskForm: {
        detailList: [
          {
            supplierName: '', // 供应商名称
            supplierCode: '', // 供应商代码
            supplierId: '', // 供应商id
            supplierClassify: '', // 供应商分类
            supplierClassifyName: '', // 供应商分类
            registerAddress: '', // 地址
            contactId: '', // 联系人id
            contactName: '', // 联系人姓名
            contactPhone: '', // 联系人电话
            contactPosition: '', // 联系人职位
            inspectType: '', // 考察类型
            newChannel: '', // 是否新渠道
            quote: '', // 是否报价
            quoteFile: '', // 报价单文件
            situation: '', // 现阶段合作情况
            target: [1], // 考察目标
            fileList: [],
            contactPersonOptions: [], // 供应商人员列表
            supplierNature: '', // 供应商性质
            supplierNatureName: '', // 供应商性质
          }
        ],
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
    }
  },
  computed: {
    title () {
      return this.id ? '修改考察计划' : '新建考察计划';
    }
  },
  created () {
    const { id, supplierCodes } = this.$route.query;
    this.id = id;
    if (id) {
      this.getDetailData()
    } else {
      const userInfo = localStorage.getItem('userInfo');
      if (!userInfo) {
        return this.$message.warning('用户信息获取失败请重新登录')
      }
      const { userName } = JSON.parse(userInfo);
      this.planForm.createUser = userName;
    }
    if (supplierCodes) {
      this.querySupplierInfo(supplierCodes)
    }
  },
  methods: {
    // 获取详情
    async getDetailData () {
      const res = await queryPlanDetailService({ id: this.id })
      if (res) {
        const { result } = res;
        this.planForm = result;
        if (result.startTime) {
          this.$set(this.planForm, 'planTime', [result.startTime, result.endTime]);
        }
        this.planForm.personList = result.personList.map(item => ({
          ...item,
          jobNumber: item.personCode
        }))
        this.taskForm.detailList = result.detailList.map(item => ({
          ...item,
          target: item.targetList,
          contactPersonOptions: [{ id: item.contactId, personName: item.contactName }],
          fileList: item.quoteFile ? [{ name: item.quoteFile }] : [],
        }));
        this.initPersonListStr()
      }
    },
    // 获取已选出差人员集合
    handleGetUserList ({ row, type }) {
      let jobNumberList = [];
      if (type == 'select') {
        const { itemUserId, jobNumber, userName } = row;
        let personItem = {
          personId: itemUserId,
          personCode: jobNumber,
          personName: userName,
          jobNumber: jobNumber,
        }
        if (this.planForm.personList.length) {
          jobNumberList = this.planForm.personList.map(item => item.jobNumber)
          if (!jobNumberList.includes(personItem.jobNumber)) {
            this.planForm.personList.push(personItem)
          }
        } else {
          this.planForm.personList.push(personItem)
        }
      } else {
        this.planForm.personList = this.planForm.personList.filter(item => item.personCode !== row.jobNumber)
      }
      this.initPersonListStr()
    },
    // 格式化出差人员
    initPersonListStr () {
      this.$set(this.planForm, 'personListStr', this.planForm.personList.map(item => item.personName).join(','));
    },
    // 显示出差人员
    showHrUserDialog () {
      this.dialogVisible = true;
    },
    // 显示供应商弹框
    showSupplierDialog (index) {
      this.itemIndex = index;
      this.supplierDialogVisible = true;
    },
    // 计划时间拆分
    splitPlanTime () {
      console.log(this.planForm.planTime)
      if (this.planForm.planTime) {
        this.planForm.startTime = this.planForm.planTime[0]
        this.planForm.endTime = this.planForm.planTime[1]
      } else {
        this.planForm.startTime = ''
        this.planForm.endTime = ''
      }
    },
    // 暂存
    async handleSave () {
      this.splitPlanTime()
      const params = {
        ...this.planForm,
        detailList: this.taskForm.detailList,
        id: this.id
      }
      const res = await stashPlanService(params, state => { this.submitLoading = state })
      if (res) {
        this.$message.success(res.message);
        this.handleCancel()
      }
    },
    // 提交
    handleSubmit () {
      this.$refs['planForm'].validate((valid) => {
        if (valid) {
          this.splitPlanTime()
          this.$refs['taskForm'].validate((valid) => {
            if (valid) {
              const { detailList } = this.taskForm;
              if (detailList.some(item => !item.target.includes(1) || item.target.length <= 1)) {
                return this.$message.warning('考察目的必须包含供应商信息选项且其余目的任选其一')
              }
              const params = {
                ...this.planForm,
                detailList,
                id: this.id
              }
              this.addPlanAction(params);
            }
          })
        }
      })
    },
    // 新增计划提交
    async addPlanAction (params) {
      const res = await addPlanService(params, state => { this.submitLoading = state })
      if (res) {
        this.$message.success(res.message);
        this.handleCancel()
      }
    },
    // 待考察供应商批量下推考察计划 获取下推供应商信息
    querySupplierInfo (supplierCodes) {
      batchQuerySupplierInfoService({ supplierCodeList: supplierCodes, ...this.pagination }).then(res => {
        if (isResponseSuccess(res)) {
          const { result } = res;
          this.taskForm.detailList = []
          result.forEach((item, index) => {
            this.itemIndex = index;
            this.addRow()
            this.handleGetSupplierInfo(item)
          })
        }
      })
    },
    // 获取供应商信息
    handleGetSupplierInfo (row) {
      if (this.itemIndex == null) {
        return;
      }
      const {
        supplierName, // 供应商编码
        supplierCode, // 供应商编码
        supplierId, // 供应商id
        supplierClassify, // 供应商分类
        supplierClassifyName, // 供应商分类
        supplierNature, // 供应商性质
        supplierNatureName, // 供应商性质
        registerAddress, // 详细地址
      } = row;
      this.taskForm.detailList[this.itemIndex].supplierName = supplierName;
      this.taskForm.detailList[this.itemIndex].supplierCode = supplierCode;
      this.taskForm.detailList[this.itemIndex].supplierId = supplierId;
      this.taskForm.detailList[this.itemIndex].supplierClassify = supplierClassify;
      this.taskForm.detailList[this.itemIndex].supplierClassifyName = supplierClassifyName;
      this.taskForm.detailList[this.itemIndex].supplierNature = supplierNature;
      this.taskForm.detailList[this.itemIndex].supplierNatureName = supplierNatureName;
      this.taskForm.detailList[this.itemIndex].registerAddress = registerAddress;
      this.getSupplierPersonData(supplierId, this.itemIndex)
      this.handleEmptyPerson()
    },
    // 获取来访人员信息
    async getSupplierPersonData (supplierId, index) {
      const res = await querySupplierPersonInfoService({ supplierId })
      if (res) {
        const { result } = res;
        this.taskForm.detailList[index].contactPersonOptions = result;
      }
    },
    addRow () {
      this.taskForm.detailList.push({
        supplierName: '', // 供应商名称
        supplierCode: '', // 供应商代码
        supplierId: '', // 供应商id
        supplierClassify: '', // 供应商分类
        supplierClassifyName: '', // 供应商分类
        registerAddress: '', // 地址
        contactId: '', // 联系人id
        contactName: '', // 联系人姓名
        contactPhone: '', // 联系人电话
        contactPosition: '', // 联系人职位
        inspectType: '', // 考察类型
        newChannel: '', // 是否新渠道
        quote: '', // 是否报价
        quoteFile: '', // 报价单文件
        situation: '', // 现阶段合作情况
        target: [1], // 考察目标
        fileList: [],
        contactPersonOptions: [], // 供应商人员列表
      });
    },
    removeRow (index) {
      this.taskForm.detailList.splice(index, 1);
    },
    onRemove (obj) {
      obj.quoteFile = '';
      obj.fileList = [];
    },
    // 供应商联系人选择后续赋值逻辑
    handelPersonSelect (val, row) {
      const { contactPhone, personPost, personName } = row.contactPersonOptions.find(item => item.id == val)
      row.contactPhone = contactPhone;
      row.contactPosition = personPost;
      row.contactName = personName;
      console.log(row)
    },
    // 切换供应商置空联系人数据
    handleEmptyPerson () {
      this.taskForm.detailList[this.itemIndex].contactPhone = '';
      this.taskForm.detailList[this.itemIndex].contactPosition = '';
      this.taskForm.detailList[this.itemIndex].contactId = '';
    },
    // 附件上传
    beforeFileUpload (obj, file) {
    },
    onUploadsuccess (obj, res) {
      const { data } = obj;
      data.fileList = [];
      if (isResponseSuccess(res)) {
        const { result } = res;
        data.fileList.push({ name: result })
        data.quoteFile = result;
        this.$refs.taskForm.validate();
      }
    },
    onUploadError (res) {
      this.$message.error(res.msg || '操作失败');
    },
    // 取消
    handleCancel () {
      this.$router.go(-1);
    },
  }
};
</script>
<style scoped>
.footer {
  margin-top: 10px;
}
.del-btn {
  float: right;
}
.add-btn {
  width: 100%;
  margin-bottom: 20px;
}
.box-card {
  margin-bottom: 10px;
}
</style>
